// BY BC Chong


/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />
/// <reference name="Sys.Extended.UI.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" />

Type.registerNamespace('AjaxControlToolkitEx');

AjaxControlToolkitEx.DropDownPanelExtenderBehavior = function(element) {
    AjaxControlToolkitEx.DropDownPanelExtenderBehavior.initializeBase(this, [element]);

    this._dropDownPanelID = null;
    this._dropDownButtonID = null;
    this._closeButtonID = null;
    this._hiddenFieldCloseButtonID = null;
    this._coverTargetControl = false;
    this._excludeHangOffset = false;
	

    this._hiddenFieldID = null;
	this._extDataHiddenFieldID = null;

    
    this._closebtnClickDelegate = null;
    this._btnClickDelegate = null;
    this._targetClickDelegate = null;
    this._bodyClickDelegate = null;
    this._keydownDelegate = null;
    this._focusDelegate = null;
    this._blurDelegate = null;
    
    this._isPnlClicked = false;    
    
}
AjaxControlToolkitEx.DropDownPanelExtenderBehavior.prototype = {
    initialize : function() {
        //console.log('dd init');
        var tar = this.get_element();
        var pnl = this.getElem(this.get_DropDownPanelID());
        var btn = this.getElem(this.get_DropDownButtonID());
        var hf = this.getElem(this.get_HiddenFieldID());
        var hfExtData = this.getElem(this.get_ExtDataHiddenFieldID());
        var closebtn = null;
        if (this.get_CloseButtonID() != null)
            closebtn = this.getElem(this.get_CloseButtonID());


        //console.log(hf.value);
        //console.log(hfExtData.value);

        pnl.style.position = 'static';
        pnl.style.display = 'none';
        pnl.style.zIndex = 0;
        pnl.setAttribute("DropdownPanelPnl", "1");
        tar.setAttribute("DropdownPanel", "1");
        tar.setAttribute("HFid", this.get_HiddenFieldID());
        tar.setAttribute("extId", this._id);
        tar.setAttribute("pnlId", this.get_DropDownPanelID());

        if (!pnl.tabIndex) pnl.tabIndex = 0;


        if (this._focusDelegate === null) {
            this._focusDelegate = Function.createDelegate(this, this._focusHandler);
        }
        //Sys.UI.DomEvent.addHandler(tar, 'focus', this._focusDelegate);
        Sys.UI.DomEvent.addHandler(pnl, 'focus', this._focusDelegate);

        if (this._blurDelegate === null) {
            this._blurDelegate = Function.createDelegate(this, this._blurHandler);
        }
        //Sys.UI.DomEvent.addHandler(tar, 'blur', this._blurDelegate);
        Sys.UI.DomEvent.addHandler(pnl, 'blur', this._blurDelegate);

        if (this._targetClickDelegate === null) {
            this._targetClickDelegate = Function.createDelegate(this, this._targetClickHandler);
        }
        Sys.UI.DomEvent.addHandler(tar, 'click', this._targetClickDelegate);
        Sys.UI.DomEvent.addHandler(pnl, 'click', this._targetClickDelegate);

        if (this._btnClickDelegate === null) {
            this._btnClickDelegate = Function.createDelegate(this, this._btnClickHandler);
        }
        $addHandler(btn, 'click', this._btnClickDelegate);


        if (this._closebtnClickDelegate === null) {
            this._closebtnClickDelegate = Function.createDelegate(this, this._closebtnClickHandler);
        }
        if (closebtn != null) {
            $addHandler(closebtn, 'click', this._closebtnClickDelegate);
        }

        if (this._bodyClickDelegate === null) {
            this._bodyClickDelegate = Function.createDelegate(this, this._bodyClickHandler);
        }
        $addHandler(document, 'click', this._bodyClickDelegate);

        if (this._keydownDelegate == null) {
            this._keydownDelegate = Function.createDelegate(this, this._KeyDownHandler);
        }
        $addHandler(document, 'keydown', this._keydownDelegate);


        
        //if (hf!=null){
        //    var visible = hf.value.split('\t')[0];
        //    if (visible != '1')
        //        this.hide();
        //    else{
        //        this.show();
        //    }
        //}
        this.registerPartialUpdateEvents();
    },

	getElem : function(id) {
		return (id=='' || id==null)?null:$get(id);
	},

    dispose : function() {
        
        var tar = this.get_element();
        var pnl = this.getElem(this.get_DropDownPanelID());
        var btn = this.getElem(this.get_DropDownButtonID());
        var hf = this.getElem(this.get_HiddenFieldID());
        var closebtn = null;
        if (this.get_CloseButtonID()!=null)
			closebtn = this.getElem(this.get_CloseButtonID());

        if (this._focusDelegate) {
            //Sys.UI.DomEvent.removeHandler(tar, 'focus', this._focusDelegate);
            Sys.UI.DomEvent.removeHandler(pnl, 'focus', this._focusDelegate);            
            delete this._focusDelegate;
        }
        if (this._blurDelegate) {
            //Sys.UI.DomEvent.removeHandler(tar, 'blur', this._blurDelegate);
            Sys.UI.DomEvent.removeHandler(pnl, 'blur', this._blurDelegate);            
            delete this._blurDelegate;
        }
        if (this._targetClickDelegate) {
            Sys.UI.DomEvent.removeHandler(tar, 'click', this._targetClickDelegate);
            Sys.UI.DomEvent.removeHandler(pnl, 'click', this._targetClickDelegate);            
            delete this._targetClickDelegate;
        }
        if (this._btnClickDelegate) {
            Sys.UI.DomEvent.removeHandler(btn, 'click', this._btnClickDelegate);
            delete this._btnClickDelegate;
        }   
        //this.set_CloseButtonID(null);
        if (this._closebtnClickDelegate){
			delete this._closebtnClickDelegate;
        }
        
                
        if (this._bodyClickDelegate) {
            Sys.UI.DomEvent.removeHandler(document, 'click', this._bodyClickDelegate);
            delete this._bodyClickDelegate;
        }

        if (this._keydownDelegate) {
            Sys.UI.DomEvent.removeHandler(document, 'keydown', this._keydownDelegate);
            delete this._keydownDelegate;
        }

        AjaxControlToolkitEx.DropDownPanelExtenderBehavior.callBaseMethod(this, 'dispose');
    },

    _partialUpdateEndRequest : function(sender, endRequestEventArgs) {
        /// <param name="sender" type="Object">
        /// Sender
        /// </param>
        /// <param name="endRequestEventArgs" type="Sys.WebForms.EndRequestEventArgs">
        /// Event arguments
        /// </param>
        AjaxControlToolkitEx.DropDownPanelExtenderBehavior.callBaseMethod(this, '_partialUpdateEndRequest', [sender, endRequestEventArgs]);

        //console.log('dd endreq');

        //var tar = this.get_element();
        //var pnl = this.getElem(this.get_DropDownPanelID());
        //var btn = this.getElem(this.get_DropDownButtonID());
        var hf = this.getElem(this.get_HiddenFieldID());
        var hfExtData = this.getElem(this.get_ExtDataHiddenFieldID());

        if (hf != null) {
            if (hf.value != '1')
                this.hide();
            else{
                this.show();
            }
        }

        if (this.get_element()) {
            // Look up result by element's ID
            var action = endRequestEventArgs.get_dataItems()[this.get_element().id];
            if ("show" == action) {
                this.show();
            } else if ("hide" == action) {
                this.hide();
            }
        }
    },

    get_DropDownPanelID : function() {
        /// <value type="String">
        /// The ID of the control to display
        /// </value>
        return this._dropDownPanelID;
    },
    set_DropDownPanelID : function(value) {
        if (this._dropDownPanelID != value) { 
            this._dropDownPanelID = value;
            this.raisePropertyChanged('DropDownPanelID');
        }
    },
    
    get_DropDownButtonID : function() {
        /// <value type="String">
        /// The ID of the control to display
        /// </value>
        return this._dropDownButtonID;
    },
    set_DropDownButtonID : function(value) {
        if (this._dropDownButtonID != value) { 
            this._dropDownButtonID = value;
            this.raisePropertyChanged('DropDownButtonID');
        }
    },


    get_HiddenFieldID : function() {
        /// <value type="String">
        /// The ID of the control to display
        /// </value>
        return this._hiddenFieldID;
    },
    set_HiddenFieldID : function(value) {
        if (this._hiddenFieldID != value) { 
            this._hiddenFieldID = value;
            this.raisePropertyChanged('HiddenFieldID');
        }
    },


    get_ExtDataHiddenFieldID : function() {
        /// <value type="String">
        /// The ID of the control to display
        /// </value>
        return this._extDataHiddenFieldID;
    },
    set_ExtDataHiddenFieldID : function(value) {
        if (this._extDataHiddenFieldID != value) { 
            this._extDataHiddenFieldID = value;
            this.raisePropertyChanged('ExtDataHiddenFieldID');
        }
    },


    
    get_CloseButtonID : function() {
        /// <value type="String">
        /// The ID of the control to display
        /// </value>
        return this._closeButtonID;
    },
    set_CloseButtonID : function(value) {
        if (this._closeButtonID != value) { 
			var closebtn = null;
			if (this._closeButtonID!=null){
				closebtn = this.getElem(this._closeButtonID);
				if (closebtn!=null){
					$removeHandler(closebtn, 'click', this._closebtnClickDelegate);			
				}
			}
			if (this._closebtnClickDelegate!=null){
				delete this._closebtnClickDelegate;
				this._closebtnClickDelegate = null;
			}
			this._closebtnClickDelegate = Function.createDelegate(this, this._closebtnClickHandler);
			
			if (value!=null){
				closebtn = this.getElem(value);
				if (closebtn!=null){
					$addHandler(closebtn, 'click', this._closebtnClickDelegate);
				}
			}
			
            this._closeButtonID = value;
            this.raisePropertyChanged('CloseButtonID');
        }
    },
    
    get_CoverTargetControl : function() {
        return this._coverTargetControl;
    },
    set_CoverTargetControl : function(value) {
        if (this._coverTargetControl != value) { 
            this._coverTargetControl = value;
            this.raisePropertyChanged('CoverTargetControl');
        }
    },

    
    get_ExcludeHangOffset : function() {
        return this._excludeHangOffset;
    },
    set_ExcludeHangOffset : function(value) {
        if (this._excludeHangOffset != value) { 
            this._excludeHangOffset = value;
            this.raisePropertyChanged('ExcludeHangOffset');
        }
    },    
    
    show: function() {
        //console.log('dd show');
        var tar = this.get_element();
        var pnl = this.getElem(this.get_DropDownPanelID());
        var btn = this.getElem(this.get_DropDownButtonID());
        var hf = this.getElem(this.get_HiddenFieldID());
        var hfExtData = this.getElem(this.get_ExtDataHiddenFieldID());
        var closebtn = null;
        if (this.get_CloseButtonID()!=null)
            closebtn = this.getElem(this.get_CloseButtonID());
        
        var clientBounds = $common.getClientBounds();
        var clientWidth = clientBounds.width;
        var clientHeight = clientBounds.height;
        /*
        var sz = $common.getSize(document.body);
        sz.width = clientWidth - 30;
        sz.height = clientHeight - 30;
        $common.setSize(document.body, sz);
        */      

        this.hangOnTarget();

        if (pnl != null && tar != null && hf !=null){
            pnl.style.display = 'block';
            hf.value = '1';
            try{
                pnl.focus();
            }catch(e){;}
        }
    },
    
    hide: function() {
        
        //console.log('dd hide');
        var tar = this.get_element();
        var pnl = this.getElem(this.get_DropDownPanelID());
        var btn = this.getElem(this.get_DropDownButtonID());
        var hf = this.getElem(this.get_HiddenFieldID());
        var hfExtData = this.getElem(this.get_ExtDataHiddenFieldID());

        //var data = JSON.parse(hfExtData.value == ''? '{}': hfExtData.value);

        var closebtn = null;
        if (this.get_CloseButtonID()!=null)
            closebtn = this.getElem(this.get_CloseButtonID());
			    

        if (pnl != null && tar != null && hf !=null){
            pnl.style.display = 'none';       
            pnl.style.zIndex = 0;
            hf.value = '0';
            		    
            //var all = document.all || document.getElementsByTagName("body")[0].getElementsByTagName("*");
            var all = document.all || document.getElementsByTagName('*'); 
            var length = all.length;
            var elements = new Array(length);
            while(length--) elements[length] = all[length];
            
            for(var i=0, ne; ne=elements[i++];) {
                var isPopup = ne.getAttribute("PopupPanel");
                var isDropdown = ne.getAttribute("DropdownPanel");
                if (isPopup == "1" ||
					isDropdown == "1"){   
                    var pe = ne.parentNode;
                    while(pe!=null && pe.nodeName.toLowerCase() != 'form'){
                        if (pe == pnl){
                            break;
                        }
                        pe = pe.parentNode;
                    }
                    if (pe == pnl){
						
                        var nehfid = ne.getAttribute("HFid");
                        var nehf = this.getElem(nehfid);
                        nehf = '0';
						
                        var neextId = ne.getAttribute("extId");
                        var neext = $find(neextId);
                        if (neext!=null)
                            neext.hideItselfOnly();
							
                        var nepnlid = ne.getAttribute("pnlId");
                        var nepnl = this.getElem(nepnlid);
                        if (nepnl!=null){
                            nepnl.style.display = 'none';
                            nepnl.style.zIndex = 0;
                            var locNePnl;
                            locNePnl = Sys.UI.DomElement.getLocation(nepnl);
                            Sys.UI.DomElement.setLocation(nepnl, locNePnl.x, locNePnl.y);
                        }
						
											
                    }
                }
            }
            
        }
    },
    
    hideItselfOnly: function() {
        
        var tar = this.get_element();
        var pnl = this.getElem(this.get_DropDownPanelID());
        var btn = this.getElem(this.get_DropDownButtonID());
        var hf = this.getElem(this.get_HiddenFieldID());
        var closebtn = null;
        if (this.get_CloseButtonID()!=null)
			closebtn = this.getElem(this.get_CloseButtonID());

			    
        if (pnl != null && tar != null && hf !=null){
            pnl.style.display = 'none';       
            pnl.style.zIndex = 0;
			hf.value = '0';
		}
    },

    hideIfTopMost: function() {
    
		var pnl = this.getElem(this.get_DropDownPanelID());
    
        var all = document.all || document.getElementsByTagName('*'); 
		var length = all.length;
		var elements = new Array(length);
		while(length--) elements[length] = all[length];
        
        var zindex = pnl.style.zIndex;
        if (!parseInt(zindex)) {
            zindex = 0;
        }            
        var topMost = true;
        for(var i=0, ne; ne=elements[i++];) {
            var isPopup = ne.getAttribute("PopupPanel");
            var isDropdown = ne.getAttribute("DropdownPanel");
            if (isPopup == "1" ||
				isDropdown == "1"){
				if ( pnl != ne
					&& parseInt(zindex) <= parseInt(ne.style.zIndex)){
					topMost = false;
						break;
						}
            }
        }
        if (topMost)
			this.hide();
        
    
    },
    
    hangOnTarget: function() {

        var tar = this.get_element();
        var pnl = this.getElem(this.get_DropDownPanelID());
        var btn = this.getElem(this.get_DropDownButtonID());
        var hf = this.getElem(this.get_HiddenFieldID());
        var hfExtData = this.getElem(this.get_ExtDataHiddenFieldID());

        var closebtn = null;
        if (this.get_CloseButtonID() != null)
            closebtn = this.getElem(this.get_CloseButtonID());
        {
            //console.log('hangon');
            //console.log(this.get_element());
            //console.log(this.get_HiddenFieldID());
            //console.log(this.get_ExtDataHiddenFieldID());
            //console.log(hf);
            //console.log(hf.value);
            //console.log(hfExtData);
            //console.log(hfExtData.value);
        }

        var data = JSON.parse(hfExtData.value == '' ? '{}' : hfExtData.value);
        if (data == null) data = {};
        //console.log(data);
        

        if (pnl != null && tar != null && hf != null) {

            var newlypopup = false;
            if (pnl != null && hf != null ) {
                if (hf.value != '1')
                    newlypopup = true;

                pnl.style.display = 'block';
                hf.value = '1';
                //pnl.focus();
            }

            //console.log(newlypopup ? 'new' : 'old');
           

            var locTar;
            locTar = Sys.UI.DomElement.getLocation(tar);

            var heightTar;
            heightTar = Sys.UI.DomElement.getBounds(tar).height;

            var offsetY = 0, offsetX = 0;
            var pe = tar.parentNode;
            while (pe != null && pe.nodeName.toLowerCase() != 'form') {
                if (pe.style != null && (pe.style.position == 'absolute'
					|| pe.style.position == 'fixed')
                    && pe.style.display != 'none') {

                    offsetY = Sys.UI.DomElement.getLocation(pe).y;
                    offsetX = Sys.UI.DomElement.getLocation(pe).x;
                    break;
                }
                pe = pe.parentNode;
            }
            if (this.get_CoverTargetControl()) {
                heightTar = 0;
            }

            if (this.get_ExcludeHangOffset()) {
                offsetX = 0;
                offsetY = 0;
            }
            //console.log(pnl.id);
            //console.log(tar.id);
            //console.log(tar);
            //console.log(locTar);

            if (newlypopup) {
                Sys.UI.DomElement.setLocation(pnl, locTar.x - offsetX, locTar.y + heightTar - offsetY);

                var oldX = locTar.x - offsetX;
                var oldY = locTar.y + heightTar - offsetY;

                data.oldX = oldX;
                data.oldY = oldY;

                //console.log(data);
            } else {

                Sys.UI.DomElement.setLocation(pnl, locTar.x - offsetX, locTar.y + heightTar - offsetY);
            }




            //var all = document.all || document.getElementsByTagName("body")[0].getElementsByTagName("*");
            var all = document.all || document.getElementsByTagName('*');
            var length = all.length;
            var elements = new Array(length);
            while (length--) elements[length] = all[length];

            var zindex = pnl.style.zIndex;
            if (!parseInt(zindex)) {
                zindex = 0;
            }

            var tarZIndex = tar.style.zIndex;
            if (!parseInt(tarZIndex)) {
                tarZIndex = 0;
            }
            zindex = parseInt(tarZIndex) + 1;

            //var pe = tar.parentNode;
            //while (pe != null && pe.nodeName.toLowerCase() != 'form') {
            //    var isPopup = pe.getAttribute("popupPanel");
            //    var isDropdown = pe.getAttribute("dropdownPanel");
            //    if (isPopup == "1") {
            //        tarZIndex = pe.style.zIndex;
            //        if (!parseInt(tarZIndex)) {
            //            tarZIndex = 0;
            //        }
            //        if (parseInt(zindex) < parseInt(tarZIndex))
            //            zindex = parseInt(tarZIndex) + 1;
            //    }
            //    if (isDropdown == "1") {
            //        var nepnlid = pe.getAttribute("pnlId");
            //        var nepnl = this.getElem(nepnlid);
            //        if (nepnl != null) {
            //            tarZIndex = nepnl.style.zIndex;
            //            if (!parseInt(tarZIndex)) {
            //                tarZIndex = 0;
            //            }
            //            if (parseInt(zindex) < parseInt(tarZIndex))
            //                zindex = parseInt(tarZIndex) + 1;
            //        }
            //    }
            //    pe = pe.parentNode;
            //}

            for (var i = 0, ne; ne = elements[i++];) {
                if (pnl != ne
                    && parseInt(zindex) <= parseInt(ne.style.zIndex))
                    zindex = parseInt(ne.style.zIndex) + 1;

                if (pnl != ne) {
                    var isPopup = ne.getAttribute("popupPanel");
                    var isDropdown = ne.getAttribute("dropdownPanel");
                    if (isPopup == "1") {
                        tarZIndex = ne.style.zIndex;
                        if (!parseInt(tarZIndex)) {
                            tarZIndex = 0;
                        }
                        if (parseInt(zindex) < parseInt(tarZIndex))
                            zindex = parseInt(tarZIndex) + 1;
                    }
                    if (isDropdown == "1") {
                        var nepnlid = ne.getAttribute("pnlId");
                        var nepnl = this.getElem(nepnlid);
                        if (nepnl != null) {
                            tarZIndex = nepnl.style.zIndex;
                            if (!parseInt(tarZIndex)) {
                                tarZIndex = 0;
                            }
                            if (parseInt(zindex) < parseInt(tarZIndex))
                                zindex = parseInt(tarZIndex) + 1;
                        }
                    }
                }

            }

            /*
            for(var i=0, ne; ne=elements[i++];) {
                if ( pnl != ne
                    && parseInt(zindex) <= parseInt(ne.style.zIndex))
                     zindex = parseInt(ne.style.zIndex) + 1;
            }
            */


            if (newlypopup) {
                if (zindex != pnl.style.zIndex && zindex > 0) {
                    pnl.style.zIndex = zindex;
                } else {
                    if (parseInt(zindex) > 0)
                        pnl.style.zIndex = parseInt(zindex) + 1;
                }
                var oldZ = pnl.style.zIndex;

                data.oldZ = oldZ;

            } else {


                //console.log('oldZ, oldX, oldY = ' + data.oldZ + ', ' + data.oldX + ', ' + data.oldY);
                //;
                Sys.UI.DomElement.setLocation(pnl, data.oldX, data.oldY);
                pnl.style.zIndex = data.oldZ;
            }

        }

        //console.log(data);
        hfExtData.value = JSON.stringify(data);
        //console.log(hfExtData.value);
        
        //this.set_extData(oldVal.toString() + '\t' + oldZ.toString() + '\t' + oldX.toString() + '\t' + oldY.toString());
    
    
    },
    
    _focusHandler: function(event) {
    },
    _blurHandler: function(event) {
        if (this._isPnlClicked){
            //this.get_element().focus();
        }
    },
    _targetClickHandler: function(event) {
        this._isPnlClicked = true;
    },
    _btnClickHandler : function(event) {
        this._isPnlClicked = true;
        //this.get_btn().focus();
        this.show();
    },   
    btnClick : function() {
        this._isPnlClicked = true;
        this.show();
    },   
    _closebtnClickHandler : function(event) {
        this.hide();
    },   
    _bodyClickHandler: function(event) {
        if (this._isPnlClicked){
            this._isPnlClicked = false;
        }else{
            //this.hide();
        }
    },
    _KeyDownHandler: function(event) {
    
        if (event.keyCode == 27 /* Escape */) {
            this.hideIfTopMost();            
        }
    }
    

    
    
    
    
}
AjaxControlToolkitEx.DropDownPanelExtenderBehavior.registerClass('AjaxControlToolkitEx.DropDownPanelExtenderBehavior', Sys.Extended.UI.BehaviorBase);
